#include <iostream>
#include <malloc.h>
#include <ctime>
#include <cstdlib>
using namespace std;

#define MAXSIZE 10

//链栈的结点定义
typedef struct LNode
{
    int data;           //数据域
    struct LNode *next; //指针域
} LNode, *PLNode;       //结点定义

void initStack(PLNode &); //初始化栈
bool isEmpty(PLNode);     //判断栈空
void push(PLNode, int);   //进栈代码
bool pop(PLNode, int &);  //出栈代码

int main(void)
{
    //初始化栈
    PLNode st;
    initStack(st);
    int res = 0;

    //入栈
    for (int i = 0; i < MAXSIZE; i++)
    {
        push(st, i);
    }

    //出栈
    for (int i = 0; i < 20; i++)
    {
        if (pop(st, res))
            cout << "出栈元素是 " << res << endl;
        else
            cout << "出栈失败" << endl;
    }

    cout << "finish" << endl;
    return EXIT_SUCCESS;
}

void initStack(PLNode &lst) //因为要改变所以要引用型
{
    lst = (PLNode)malloc(sizeof(LNode));
    lst->next = NULL; //指定为栈空状态
}

bool isEmpty(PLNode lst) //判断栈空
{
    if (lst->next == NULL)
        return true;
    else
        return false;
}

void push(PLNode lst, int x)    //入栈
{
    PLNode pNew = (PLNode)malloc(sizeof(LNode));
    pNew->data = x;
    pNew->next = NULL;

    //头插法
    pNew->next = lst->next;
    lst->next = pNew;
}

bool pop(PLNode lst, int &x)    //出栈
{
    PLNode p = lst->next;
    if (lst->next == NULL)
        return false;

    //单链表的删除操作
    x = p->data;
    lst->next = p->next;
    free(p);
    return true;
}